#include "application.h"
//#include <qDebug.h>
#include <QtWebKit>

Application::Application(const QString &id, int &argc, char **argv)
    : QtSingleApplication(id, argc, argv)
{
#if 0x1
    QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8"));
    QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8"));

    QCoreApplication::setOrganizationDomain("akio.miyoshi");
    QCoreApplication::setOrganizationName("akio.miyoshi");
    QCoreApplication::setApplicationName("yt_front");
    QSettings settings(
            QSettings::IniFormat, //QSettings::NativeFormat,
            QSettings::UserScope, // QSettings::SystemScope,
            QCoreApplication::organizationName(),
            QCoreApplication::applicationName()
            );

    QWebSettings *webSettings = QWebSettings::globalSettings();
    webSettings->setAttribute(QWebSettings::JavascriptEnabled, true);
    webSettings->setAttribute(QWebSettings::PluginsEnabled, true);
    webSettings->setAttribute(QWebSettings::LocalContentCanAccessRemoteUrls, true);
#endif
    f_db = this->openDB();
    if(!f_db.isOpen())
    {
        QMessageBox::information(0, "Error", QString("(!m_db.isOpen())"));
    }
    f_download_exe = this->getDownloadExe();
    qDebug() << "[f_download_exe]" << f_download_exe;
}

#if 0x0
Application::Application ( int & argc, char ** argv )
    : QtSingleApplication(argc, argv)
{
#if 0x1
    QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8"));
    QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8"));

    QCoreApplication::setOrganizationDomain("akio.miyoshi");
    QCoreApplication::setOrganizationName("akio.miyoshi");
    QCoreApplication::setApplicationName("yt_front");
    QSettings settings(
            QSettings::IniFormat, //QSettings::NativeFormat,
            QSettings::UserScope, // QSettings::SystemScope,
            QCoreApplication::organizationName(),
            QCoreApplication::applicationName()
            );

    QWebSettings *webSettings = QWebSettings::globalSettings();
    webSettings->setAttribute(QWebSettings::JavascriptEnabled, true);
    webSettings->setAttribute(QWebSettings::PluginsEnabled, true);
    webSettings->setAttribute(QWebSettings::LocalContentCanAccessRemoteUrls, true);
#endif
    f_db = this->openDB();
    if(!f_db.isOpen())
    {
        QMessageBox::information(0, "Error", QString("(!m_db.isOpen())"));
    }
    f_download_exe = this->getDownloadExe();
    qDebug() << "[f_download_exe]" << f_download_exe;
}
#endif

bool Application::prepareDirectory(const QString &a_abs_path)
{
    qDebug() << "[prepareDirectory(1)]" << a_abs_path;
    if(QFileInfo(a_abs_path).exists())
    {
        if(!QFileInfo(a_abs_path).isDir()) return false;
        return true;
    }
    else
    {
        QString v_abs_path = a_abs_path;
        v_abs_path.replace("\\", "/");
        int v_slash_1st = v_abs_path.indexOf("/");
        if(v_slash_1st == -1) return false;
        QString v_dir_root = v_abs_path.mid(0, v_slash_1st+1);
        qDebug() << "[prepareDirectory(2)]" << v_dir_root;
        QString v_dir_name = v_abs_path.mid(v_slash_1st+1);
        qDebug() << "[prepareDirectory(3)]" << v_dir_name;
        return QDir(v_dir_root).mkpath(v_dir_name);
    }
}

QString Application::prepareMDB()
{
    Q_ASSERT(!QCoreApplication::organizationDomain().isEmpty());
    Q_ASSERT(!QCoreApplication::organizationName().isEmpty());
    Q_ASSERT(!QCoreApplication::applicationName().isEmpty());

    QString v_data_loc = QDesktopServices::storageLocation(QDesktopServices::DataLocation);
    qDebug() << "[v_data_loc]" << v_data_loc;
    QString v_abs_dir = QFileInfo(v_data_loc).dir().absolutePath();
    qDebug() << "[v_abs_dir]" << v_abs_dir;
    QString v_mdb_abs_path = v_data_loc + ".mdb";
    qDebug() << "(1)" << v_mdb_abs_path;
    QString v_mdb_dir_path = QFileInfo(v_mdb_abs_path).dir().absolutePath();
    prepareDirectory(v_mdb_dir_path);
    if(!QFileInfo(v_mdb_abs_path).exists())
    {
        QFile(":/mdb/empty2k.mdb").copy(v_mdb_abs_path);
        QFile(v_mdb_abs_path).setPermissions(QFile::WriteUser);
    }
    return v_mdb_abs_path;
}

QSqlDatabase Application::openDB()
{
#if 0x1
    QString v_db_path = prepareMDB();
    //TODO: ダウンロードボタンの実装
    QSqlDatabase v_db = QSqlDatabase::addDatabase("QODBC");
    v_db.setDatabaseName(
            QString("DRIVER={Microsoft Access Driver (*.mdb)};FIL={MS Access};DBQ=%1;")
            .arg(v_db_path)
            );
#else
    //TODO: .sqlite を v_data_location から発見する。
    QString v_db_path = "C:/usr/local/data/yt_front.sqlite";
    QSqlDatabase v_db = QSqlDatabase::addDatabase("QSQLITE");
    v_db.setDatabaseName(v_db_path);
#endif
    v_db.open();
    QSqlQuery v_query;
    v_query.prepare("create table xyz(a integer, b text)");
    v_query.exec();
    return v_db;
}

QString Application::getDownloadExe()
{
    QString v_app_dir_path = QCoreApplication::applicationDirPath();
    qDebug() << "[QCoreApplication::applicationDirPath]" << v_app_dir_path;
    QString v_dl_exe_path = v_app_dir_path + "/yt_download.exe";
    if(QFileInfo(v_dl_exe_path).exists())
    {
        return v_dl_exe_path;
    }
    return "C:/usr/local/release/yt_download.exe";
}
